// scripts/check_users.js
const { Sequelize } = require('sequelize');

// 数据库配置
const sequelize = new Sequelize('lingxi_system', 'root', '888mei525', {
  host: '127.0.0.1',
  dialect: 'mysql',
  logging: false
});

// 用户模型定义（匹配实际数据库表结构）
const User = sequelize.define('user', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: Sequelize.STRING(50),
    allowNull: false
  },
  email: {
    type: Sequelize.STRING(100),
    allowNull: false
  },
  password: {
    type: Sequelize.STRING(100),
    allowNull: false
  },
  role: {
    type: Sequelize.ENUM('admin', 'user', 'auditor'),
    allowNull: false,
    defaultValue: 'user'
  },
  status: {
    type: Sequelize.ENUM('active', 'inactive', 'locked'),
    allowNull: false,
    defaultValue: 'active'
  },
  lastLoginAt: {
    type: Sequelize.DATE,
    allowNull: true,
    field: 'last_login_at'
  },
  createdAt: {
    type: Sequelize.DATE,
    allowNull: false,
    field: 'created_at'
  },
  updatedAt: {
    type: Sequelize.DATE,
    allowNull: false,
    field: 'updated_at'
  }
}, {
  tableName: 'users',
  timestamps: true,
  underscored: true
});

async function checkUsers() {
  try {
    // 测试数据库连接
    await sequelize.authenticate();
    console.log('数据库连接成功');
    
    // 查找所有用户
    const users = await User.findAll({
      attributes: ['id', 'name', 'email', 'role', 'status']
    });
    
    console.log('\n用户列表:');
    if (users.length > 0) {
      users.forEach(user => {
        console.log(`ID: ${user.id}, 姓名: ${user.name}, 角色: ${user.role}, 状态: ${user.status}`);
      });
    } else {
      console.log('数据库中没有用户');
    }
    
    // 查找管理员用户
    const adminUsers = await User.findAll({
      where: {
        role: 'admin'
      },
      attributes: ['id', 'name', 'email', 'role', 'status']
    });
    
    console.log('\n管理员用户:');
    if (adminUsers.length > 0) {
      adminUsers.forEach(user => {
        console.log(`ID: ${user.id}, 姓名: ${user.name}, 邮箱: ${user.email}`);
      });
    } else {
      console.log('未找到管理员用户');
      
      // 创建默认管理员用户
      console.log('\n正在创建默认管理员用户...');
      const adminUser = await User.create({
        name: 'admin',
        email: 'admin@example.com',
        password: '123456',
        role: 'admin',
        status: 'active'
      });
      
      console.log('默认管理员用户创建成功:');
      console.log(`ID: ${adminUser.id}, 姓名: ${adminUser.name}, 角色: ${adminUser.role}`);
    }
    
    await sequelize.close();
  } catch (error) {
    console.error('检查用户数据失败:', error.message);
    process.exit(1);
  }
}

// 执行脚本
checkUsers();